<?php
namespace app\index\controller;
use app\index\model\Api;
use app\index\model\Param;
use think\Controller;
use app\index\model\ApiGroup as ApiGroupModel;
use think\Request;
use app\index\model\User as UserModel;

class Index extends Controller
{
    public function index()
    {
        $model = new UserModel();
        $this->assign('userList',$model->getUserList());
        $this->assign('url_route',get_url_route());
        return $this->fetch();
    }

    //获取有数据的分组
    public function getGroupList(Request $request)
    {
        $model = new ApiGroupModel();

        $list = $model->getGroupList($request->param('name'));

        return $list ? ajaxReturn($list) : ajaxReturn('暂无数据');
    }

    //根据分组获取分组下的API数据
    public function getApiListByGroupId(Request $request)
    {
        $id = $request->param("id");
        $name = $request->param("name");
        if(!$id){
            return ajaxReturn('参数错误');
        }
        $user_id = $this->getUserIdByName($name);
        if($user_id){
            $list = Api::all(['group_id'=>$id,'status'=>1,'user_id'=>$user_id]);
        }else{
            $list = Api::all(['group_id'=>$id,'status'=>1]);
        }
        foreach ($list as $k => &$v){
            $v->param = Param::all(['type'=>0,'status'=>1,'api_id'=>$v->id]);
            $v->result = Param::all(['type'=>1,'status'=>1,'api_id'=>$v->id]);
        }
        return $list ? ajaxReturn($list) : ajaxReturn('暂无数据');
    }

    //根据姓名获取用户id
    protected function getUserIdByName($name)
    {
        $user = UserModel::get(['name'=>$name]);
        return $user ? $user->id : '';
    }

}
